package com.ghck.shop.config;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@Configuration
@MapperScan("com.ghck.shop.dao")
@EnableTransactionManagement
public class DaoConfiguration {

	private Logger logger = LoggerFactory.getLogger(DaoConfiguration.class);
	
	@Configuration
    @Profile(UserProfile.INTG)
    @PropertySource(value = {"classpath:/intg/jdbc.properties"})
    static class DbIntgConfiguration {
    }
	
	@Configuration
    @Profile(UserProfile.PROD)
    @PropertySource(value = {"classpath:/prod/jdbc.properties"})
    static class DbProdConfiguration {
    }
	
	@Autowired
    private Environment env;
    
	@Bean
    public DataSource mysqlDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        String dbUrl = env.getProperty("mysql.url");
        String dbUsername = env.getProperty("mysql.username");
        String dbPassword = env.getProperty("mysql.password");
        dataSource.setUrl(dbUrl);
        dataSource.setUsername(dbUsername);
        dataSource.setPassword(dbPassword);
        dataSource.setValidationQuery("select 1");
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setMaxWait(60000);
        dataSource.setMaxActive(20);
        dataSource.setInitialSize(1);
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        return dataSource;
    }

	
	@Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        logger.info("SqlSessionFactory--begin to set dataSource--");
        sqlSessionFactory.setDataSource(mysqlDataSource());
        Resource resource = new ClassPathResource("mybatis-config.xml");
        sqlSessionFactory.setConfigLocation(resource);
        return sqlSessionFactory.getObject();
    }
	
	@Bean
    public DataSourceTransactionManager transactionManager() {
    	logger.info("DataSourceTransactionManager--begin to set dataSource--");
        return new DataSourceTransactionManager(mysqlDataSource());
    }

}